<!-- 管理员列表
  从分页组件传了两个事件过来changLimit、changPage
-->
<template>
    <div class="main"  @scroll.passive="scrollTop($event)">
        <!-- 管理员头部 -->
        <div class="admin-top">
            <el-space wrap :size="10">
                <el-input v-model="input" placeholder="请输入管理员名称" clearable />
                <el-button type="primary" :icon="Search" @click="search()">查找</el-button>
                <el-button type="primary" :icon="Edit" @click="add()">添加</el-button>
            </el-space>
        </div>
        <!-- 管理员列表 -->
        <div class="admin-toble">
            <el-table :data="tableData" border style="width: 100%;">
                <el-table-column prop="id" label="管理员ID" align="center" />
                <el-table-column prop="username" label="管理员名称" align="center" />
                <el-table-column prop="realname" label="真实姓名" align="center" />
                <el-table-column prop="phone" label="电话" align="center" />
                <el-table-column label="管理员角色" align="center">
                    <template #default="scope">
                        <template v-for="item in handlerRoleName(scope.row.roleIds)" :key="item">
                            <el-tag>{{item.label}}</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <div>
                            <el-button type="primary" @click="handleEdit( scope.row)">修改</el-button>
                            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加和修改弹出框 -->
            <el-dialog v-model="dialogFormVisible" :title="bool?'创建':'修改'" destroy-on-close>
                <el-form :model="form" status-icon :rules="rules" ref="ruleFormRef">
                    <el-form-item label="用户名" prop="username" class="is-required">
                        <el-input v-model.trim="form.username" autocomplete="off"   :disabled="bool==false"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password"  class="is-required"   v-if="bool">
                        <el-input v-model.trim="form.password" autocomplete="off" type="password" show-password/>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone"  class="is-required">
                        <el-input v-model.trim="form.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realname"  class="is-required">
                        <el-input v-model.trim="form.realname" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色" :class="bool?'':'is-required'" :prop="bool?'':'roleIds'">
                        <template #default="scope">
                            <el-select v-model="form.roleIds" multiple placeholder="请选择" style="width: 240px">
                                <el-option v-for="item in roleManage" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addConfirmation(ruleFormRef)"  type="primary">{{bool?'新增':'修改'}}</el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas"   @page-change="pageChange" ></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main"  :visibility-height="0"  v-if="bool"/>
    </div>
</template>
<script  setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { Search, Edit } from '@element-plus/icons-vue'
import { ClassPagination } from "#/index";
import { get, post } from "@/utils/request";
import Paging from "@/components/paging/Paging.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
let input = ref('')//搜索框
const main = ref()  //滚动组件对象的引用
let rollHeight = ref(0)  //滚动距离
let neme = ref("") //搜索传递的值
const tableData: TypeAdmin[] = reactive([]) //管理员列表
const dialogFormVisible = ref(false) //控制修改框是否可见
let roleManage: TypeItems[] = reactive([]) //角色枚举
let bool = ref(true) //判断是添加还是修改

//分页数据
let pagingDatas = reactive(new ClassPagination())
//管理员列表
const adminList = () => {
    //管理员列表请求数据
    let data = {
        _gp: "admin",
        _mt: "list",
        username: neme.value,
        page: pagingDatas.page,
        limit: pagingDatas.limit
    }
    get(data).then((res) => {
        console.log(res)
        if (200 == res.errno) {
            tableData.length = 0 //清空数组
            pagingDatas.total = res.data.total  //把数据里的总条数赋值给总条数
            tableData.push(...res.data.items) //添加进管理员列表数组
            return Promise.resolve()
        } else {
            ElMessage.error(res.errmsg)
            pagingDatas.total = 0
            return Promise.reject(res.errmsg)
        }
    }).then(() => {
        //角色枚举请求数据
        let data = {
            _gp: "admin.role",
            _mt: "options",
        }
        get(data).then((res) => {
           if(200==res.errno){
            roleManage.length = 0,
            roleManage.push(...res.data)   //添加进角色枚举数组
           }else{
             return Promise.reject(res.errmsg)
           }
        })
    })
}

//获取角色枚举名字
let handlerRoleName=(roleIds:number[])=>{
     if(roleIds.length==0) return [];
     return  roleManage.filter(v=> roleIds.includes(v.value))
}
//增加弹出框数据
const form:TypeAdmin = reactive({
    username: '',  //用户名
    password: '',  //密码
    phone: "",  //电话
    realname: "", //真实姓名
    id: 0,
    roleIds: [] //角色
})
//  用户验证
const validateName = (rule: string, value: string, callback: Function) => {
    if (value === '') {
        callback(new Error('请输入账户'))
    }
    callback()
}
//用户密码验证
const validatePass = (rule: string, value: string, callback: Function) => {
    var regexp = /^[a-zA-Z0-9_]{4,16}$/
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!regexp.test(value)) {
        callback(new Error('密码必须是字母、数字、下划线,长度4-16位'))
    }
    callback()
}

//电话验证
const validatePhone = (rule: string, value: string, callback: Function) => {
    var regexp = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    if (value === '') {
        callback(new Error('请输入手机号码'))
    } else if (!regexp.test(value)) {
        callback(new Error('手机号码格式不正确'))
    }
    callback()
}
//姓名验证
const validateRealname = (rule: string, value: string, callback:Function) => {
    var regexp = /^[\u4E00-\u9FA5]{1,}$/;
    if (value === '') {
        callback(new Error('请输入姓名'))
    } else if (!regexp.test(value)) {
        callback(new Error('姓名必须是中文'))
    }
    callback()
}
//角色验证
const validateRoleIds = (rule: string, value: string, callback: Function) => {
    if (value.length==0) {
        callback(new Error('请选择用户角色'))
    }
    callback()
}
//验证规则
const rules = reactive({
    username: [{ validator: validateName, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    realname: [{ validator: validateRealname, trigger: 'blur' }],
    roleIds:[{ validator: validateRoleIds, trigger: 'change' }]
})
//搜索
const search = () => {
    neme.value = input.value
    pagingDatas.page = 1
    adminList()
}
//添加
let newForm = {...form} 
const add = () => {
    dialogFormVisible.value = true 
    bool.value = true
    Object.assign(form,newForm)
}
let roleIds = ref([])  //存储角色管理
//修改
const handleEdit = (row: TypeAdmin) => {
     dialogFormVisible.value = true
     bool.value = false
     roleIds.value = form.roleIds = row.roleIds //把当前行的角色管理赋值给存储角色管理的数组
     Object.assign(form,row) //合并row对象
     delete form.password //删除不要的密码属性
}
//修改和新增确定
const addConfirmation = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let data = {
                _gp: "admin",
                _mt: bool.value==true?"create":"edit",
                adminDTO: JSON.stringify({ ...form })
            }
            post(data).then((res) => {
                if (200 == res.errno) {
                    dialogFormVisible.value = false
                    ElMessage.success(bool.value==true?"添加成功":"修改成功")
                    adminList()
                }
            })
        } else {
            console.log('error submit!')
            ElMessage.error("新增失败")
            return false
        }
    })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if(bool.value==false){
    form.roleIds = roleIds.value
  }else{
    form.roleIds = [] //清空角色数组
  }
  formEl.resetFields() //重置该表单项，将其值重置为初始值，并移除校验结果
}
//删除
const handleDelete = (row: TypeAdminROW) => {
    // console.log(row)
    let data = {
        _gp: "admin",
        _mt: "delete",
        id: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        }
    ).then(() => {
        get(data).then((res) => {
            if (200 == res.errno) {
                ElMessage.success("删除成功")
                adminList()
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    })
        .catch(() => {
            ElMessage.info("取消操作")
        })
}

//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    adminList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}



//滚动事件
let scrollTop=(e:Event)=>{
    rollHeight.value=Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight,(val:number)=>{
//    console.log(val);
  bool.value = val>60
})
adminList()
</script>
<style scoped lang="less">
.admin-top {
    margin: 15px 0px;

    .el-input {
        width: 15vw;
    }
}

.admin-toble {
    .el-tag {
        margin-right: 5px;
        margin-bottom: 2px;
    }

    .el-dialog {
        .el-form {
            &::v-deep .el-form-item__label {
                width: 12vw;
            }

            text-align: center;

            .el-form-item__content {
                .el-input {
                    width: 25vw;
                }
            }
        }
    }
}
</style>